﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using Exec;

namespace Net
{
    public class Client: IValue
    {
        Socket c_socket;

        public Client()
        {
            c_socket =
                new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        public bool Connect(string ip)
        {
            IPEndPoint serverEP;

            try
            {
                serverEP = new IPEndPoint(IPAddress.Parse(ip), Net.port);
                c_socket.Connect(serverEP);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }

            return true;
        }

        public void Disconnect()
        {
            c_socket.Shutdown(SocketShutdown.Both);
            c_socket.Close();
        }

        public bool Mediate(string c)
        {
            int size;

            byte[] sbuf = Encoding.UTF8.GetBytes(c);    //send buffer
            byte[] rbuf = new byte[512];                //recv buffer

            try
            {
                c_socket.Send(sbuf);

                size = c_socket.Receive(rbuf, 512, SocketFlags.None);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }

            Console.WriteLine(Encoding.UTF8.GetString(rbuf, 0, size));

            return true;
        }
    }
}
